import Vue from 'vue'
import Router from 'vue-router'

import store from '@/store'

import { asyncRoutes } from '@/router/dynamicRoute.js'

Vue.use(Router)

/* Layout */
import Layout from '@/layout'

export const staticRoutes = [
  {
    path: '/login',
    component: () => import('@/views/Login/index'),
    hidden: true
  },
  {
    path: '/',
    component: Layout,
    redirect: '/workbench'
  },
  {
    path: '/roleAdd',
    component: () => import('@/views/System/Role/AddRole')
  },
  {
    path: '/parking/AddCard',
    component: () => import('@/views/Car/CarCard/AddCard')
  },
  {
    path: '/exterpriseAdd',
    component: () => import('@/views/Park/Building/AddPark/index')
  },
  {
    path: '/exterpriseDetail',
    component: () => import('@/views/Park/Building/LookPark/index')
  },
  {
    path: '/workbench',
    component: Layout,
    children: [{
      path: '',
      component: () => import('@/views/Workbench/index'),
      meta: { title: '工作台', icon: 'el-icon-data-line' }
    }]
  },

  
 
  {
    path:'/heimaUploading',
    component: Layout,
    meta: { title: '上传功能', icon: 'el-icon-loading' },
    children: [{
      path: '',
      component: () => import('@/views/Uploading/index'),
      meta: { title: '多文件上传', icon: 'el-icon-loading' }
    },
  {
    path:'gtxy',
    component: () => import('@/views/Uploading/gtxy'),
    meta: { title: '多文件上传(藤)', icon: 'el-icon-loading' }
  }]
  },
  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  },
  {
    path: '/roleEdit/:id',
    component: () => import('@/views/System/Role/EditRole/index'),
    meta: { title: '编辑角色' },
    hidden: true
  }
]

const createRouter = () => new Router({
  // mode: 'history', // require service support
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes: staticRoutes
})

const router = createRouter()

// 重置路由方法
export function resetRouter() {
  // 得到一个全新的router实例对象
  const newRouter = createRouter()
  // 使用新的路由记录覆盖掉老的路由记录
  router.matcher = newRouter.matcher
}

// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
      return item.split(':')[0]
  })
  return [...new Set(newArr)]
}

// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
      const arr = item.split(':')
      return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}

function getRoutes(firstRoutePerms, secondRoutePerms) {
  // 根据一级和二级对动态路由表做过滤 return出去过滤之后的路由表
  // 1. 根据一级路由对动态路由表做过滤
  let top1Route = asyncRoutes.filter(item=>firstRoutePerms.includes(item.permission))
  top1Route = top1Route.map(item => {
    // 2. 对二级路由做过滤
    return {
      ...item,
      children: item.children.filter(item => secondRoutePerms.includes(item.permission))
    }
  })
  return top1Route
}

router.beforeEach(async(to, from, next) => {
  // let token = localStorage.getItem('my-token') ? JSON.parse(localStorage.getItem('my-token')).user.token : null
  // console.log(token);

  if (to.path === '/login') {
    next()
  } else {
    const token = store.state.user.token
    if (token) {
      next()
      // 获取权限列表   || from.path==='/login'
      if (!store.state.user.profile.id) {
        const permissions = await store.dispatch('user/getProfile')
        // console.log('权限列表', permissions);
        // 处理一级和二级菜单标识
        const firstRoutePerms = getFirstRoutePerms(permissions)
        // console.log(firstRoutePerms)
        const secondRoutePerms = getSecondRoutePerms(permissions)
        // console.log(secondRoutePerms)

        // 根据权限标识过滤路由表
        const filterRoutes = getRoutes(firstRoutePerms, secondRoutePerms)
        //addRoute动态添加路由
        // '*:*:*' 表示管理员，拥有所有的权限
        if (permissions.includes('*:*:*')) {
            // 添加路由
            asyncRoutes.forEach(item => router.addRoute(item))      
            store.commit('menu/setMenuList', asyncRoutes)           
        } else {
            // 添加路由
            filterRoutes.forEach(item => router.addRoute(item))       
            store.commit('menu/setMenuList', filterRoutes)           
        }
    }
    } else {
      next('/login')
    }
  }
})


export default router
